<?php

require_once($_SERVER['DOCUMENT_ROOT'] . '/Mapi/vendor/alipay_km/config.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/Mapi/vendor/alipay_km/AopClient.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/Mapi/vendor/alipay_km/AlipayTradeAppPayRequest.php');

        /*------------------------------------------------------ */
		//-- 获取支付宝回调通知的原始数据
        /*------------------------------------------------------ */
        $raw_post_data = file_get_contents('php://input');
        $post_data = '';
		//日志记录支付宝返回报文信息
		if(count($_REQUEST)>0){
			foreach($_REQUEST as $key=>$value){
				
				$post_data.= '&'.$key.'='.$value;
			}
			api_pay_logger($post_data);
		}else{
			//exit('params_fail');
		}

       
        $out_trade_no = isset($_REQUEST['out_trade_no']) ? $_REQUEST['out_trade_no'] : ''; //商户订单号
        $trade_no     = isset($_REQUEST['trade_no']) ? $_REQUEST['trade_no'] : ''; //支付宝交易号      
        $trade_status = isset($_REQUEST['trade_status']) ? $_REQUEST['trade_status'] : ''; //交易状态
        $total_amount = isset($_REQUEST['total_amount']) ? $_REQUEST['total_amount'] : '';//支付金额
        $pay_date 	  = isset($_REQUEST['gmt_payment']) ? $_REQUEST['gmt_payment'] : '';//支付时间
		
		$passback_params = isset($_REQUEST['passback_params']) ? urldecode($_REQUEST['passback_params']) : '';//回传参数
		$passback_params = json_decode($passback_params,true);
	
		/*------------------------------------------------------ */
		//-- 回调验签
        /*------------------------------------------------------ */
		$Client = new AopClient();//实例化支付宝sdk里面的AopClient类
        $Client->alipayrsaPublicKey = $alipay_config['ali_public_key'];//支付宝公钥
        $verify_result = $Client->rsaCheckV1($_REQUEST,'','RSA2');
		//============================================================================
		
		//$verify_result =true;
		if ($verify_result) {
			api_pay_logger('row:verify_success');
			//判断交易状态
            if (in_array($trade_status, array('TRADE_FINISHED', 'TRADE_SUCCESS'))) {

				if($trade_status=='TRADE_SUCCESS'){//交易成功修改订单状态
					
                    switch($passback_params["order_type"]){
                        case 1://普通订单
							
							require_once($_SERVER['DOCUMENT_ROOT'] . '/Mapi/library/App_Init.php');
                            require_once($_SERVER['DOCUMENT_ROOT'] . '/Mapi/controller/orderAction.php');
							
							$order = new orderAction();
                            $res_data = $order->pay_success($passback_params["order_id"],$trade_no,1,'支付宝');
				
                            api_pay_logger($passback_params["order_id"].':'.$res_data['msg']);
//                            $log["is_paid"] = 1;
//                            $log["pay_type"] = 1;//1-支付宝
//                            $log["back"] = 'pt'.$data;
//                            insert_pay_log($log);
                            break;
                        case 2://团购订单
                            require_once($_SERVER['DOCUMENT_ROOT'] . '/Mapi/library/App_Init.php');
                            require_once($_SERVER['DOCUMENT_ROOT'] . '/Mapi/controller/pintuanAction.php');

                            $order = new pintuanAction();
                            $res_data = $order->curl_pay_success($passback_params["order_id"],$trade_no,1,'支付宝');

                            api_pay_logger($passback_params["order_id"].':'.$res_data['msg']);


//                            header("Content-type: text/html; charset=utf-8");
//                            include $_SERVER['DOCUMENT_ROOT']."/Mapi/library/curl.class.php";
//                            $http_host =  "http://".$_SERVER['HTTP_HOST'];
//                            $order_id = $passback_params["order_id"]?$passback_params["order_id"]:0;
//
//                            $curl = new curl($http_host);
//                            $apiurl="/Mapi/?url=/pintuan/curl_pay_success";
//                            $parameter=array("order_id" =>$order_id);
//
//                            $result = $curl->post($apiurl,$parameter,true);
//                            $res_data = $curl->object_array(json_decode($result));
//                            $data = $res_data['response'];
//
//                            api_pay_logger('pt'.$data);
                            break;
                        case 3://充值
                            require_once($_SERVER['DOCUMENT_ROOT'] . '/Mapi/library/App_Init.php');
                            require_once($_SERVER['DOCUMENT_ROOT'] . '/Mapi/controller/orderAction.php');

                            $order = new orderAction();
                            $res_data = $order->recharge_success($passback_params["order_id"],$total_amount);

                            api_pay_logger($passback_params["order_id"].':'.$res_data['msg']);
                            break;
                        default:
						    api_pay_logger('83：'.$trade_status);
                            break;
                    }
					 exit('success');

				}else{
//				    $log["is_paid"] = 0;
//                    $log["pay_type"] = 1;//1-支付宝
//                    $log["back"] = $post_data;
//				    insert_pay_log($log);
                }
				
                //返回给支付宝回调结果
				
                exit('success');
            }
			
			
			exit('success'); 
			
		}else{
//            $log["is_paid"] = 0;
//            $log["pay_type"] = 1;//1-支付宝
//            $log["back"] = $post_data;
//            insert_pay_log($log);
			api_pay_logger('row:verify_fail');
			exit('fail');
		}
        
     
			


	//api日志记录
    function api_pay_logger($log_content)
    {
        date_default_timezone_set("Asia/Shanghai");
        $max_size = 100000;
        $path = $_SERVER['DOCUMENT_ROOT']."/Mapi/log/" . date("Y-m-d") . "/";
        if(!file_exists($path))
        {
            mkdir($path,0777,true);
        }
        $log_filename = $path."/alipay_log.txt";
        if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
        file_put_contents($log_filename, date('Y-m-d H:i:s')." ".$log_content."\r\n", FILE_APPEND);
    }
	
?>